package org.itboys.mobile.service.mongo.mobile.member;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.image.ImageUtils;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mdl.conmon.ErroException;
import org.itboys.mdl.conmon.Finals;
import org.itboys.mdl.dto.comment.MdlCommentDto;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.product.SundayProductMapper;
import org.itboys.mobile.dto.member.SundayMemberDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mongo.mobile.collection.MdlMobileCollectionService;
import org.itboys.mobile.service.mongo.mobile.comment.MdlMobileCommentService;
import org.itboys.mobile.service.mongo.mobile.common.SundayMobileCidService;
import org.itboys.mobile.service.mongo.mobile.common.SundayMobileCodeService;
import org.itboys.mobile.util.Md5UtilJx;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created on 2017/11/30.
 * @author 朱坤涛
 * emarl:kuntao330@163.com
 */
@Service
public class SundayMobileMemberService extends BaseMongoService<SundayMember>{

    @Autowired
    private SundayMobileCodeService codeService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayMobileCidService cidService;
    @Autowired
    private MdlMobileCollectionService collectionService;
    @Autowired
    private MdlMobileCommentService commentService;
    @Autowired
    private SundayProductMapper productMapper;
    @Resource(name="mobileDs")
    private MongoDataSource mongoDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mongoDataSource;
    }
    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }

    /**
     * 用户注册
     * @param mobile
     * @param password
     * @param code
     * @param recommendId
     * @return
     */
    public SundayMemberDto register(String mobile,String password,String code,Long recommendId){
        Map<String, Object> param =new HashMap<String,Object>();
        int check_code=codeService.checkCode(mobile,code, SundayCommonConstants.validate_code_type_register);
        if(check_code!=0){
         throw new ErrorException("验证码错误。");
        }
        param.clear();
        param.put("isDeleted",0);
        //实际校验mobile字段
        param.put("mobile",mobile);
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            throw new ErrorException("此手机号已被注册。");
        }
        SundayMember member = new SundayMember();
        member.setStatus(0);
        member.setMobile(mobile);
        member.setUserType(SundayCommonConstants.USER_TYPE_MEMBER);
        member.setPassword(Digests.md5(password));
        if(LongUtil.isNotZreo(recommendId)){
            SundayMember salesMan=super.getById(recommendId);
            if(salesMan!=null){
                if(salesMan.getUserType()!=SundayCommonConstants.USER_TYPE_SALESMAN){
                    throw new ErrorException("推荐人类型不是销售员");
                }
                member.setRecommenderId(recommendId);
                member.setAgentId(salesMan.getAgentId());
            }
        }else {
            member.setAgentId(getDefaultAgent());
        }
        super.save(member);
        return packageDtoSingle(member);
    }

    /**
     * 代理商给销售员注册账号
     * @return
     */
/*    public SundayMemberDto registerSalesMan(String mobile,Long agentId,String code){
        Map<String, Object> param =new HashMap<String,Object>();
        param.clear();
        param.put("isDeleted",0);
        //实际校验mobile字段
        param.put("mobile",mobile);
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            throw new ErrorException("此手机号已被注册。");
        }
        int check_code=codeService.checkCode(mobile,code, SundayCommonConstants.validate_code_type_register);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
        SundayMember salesMan=new SundayMember();
        salesMan.setMobile(mobile);
        salesMan.setAgentId(agentId);
        salesMan.setUserType(SundayCommonConstants.USER_TYPE_SALESMAN);
        salesMan.setSalesManStatus(SundayCommonConstants.YES);
        super.save(salesMan);
        return packageDtoSingle(salesMan);


    }*/


    /**
     * 代理商生成维修工和销售员
     * @param mobile
     * @param agentId
     * @param userName
     * @param password
     * @param nickName
     * @return
     */
    public SundayMemberDto registerMember(Long agentId,String userName,String password,String nickName,String mobile,Integer type){
        Map<String, Object> param =new HashMap<String,Object>();
        param.clear();
        param.put("isDeleted",0);
        //实际校验mobile字段
        param.put("mobile",mobile);
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            throw new ErrorException("此手机号已被注册。");
        }
        SundayMember member=new SundayMember();
        member.setAgentId(agentId);
        if(type==SundayCommonConstants.USER_TYPE_SELLER){
            member.setUserType(SundayCommonConstants.USER_TYPE_SELLER);
        }else if(type==SundayCommonConstants.USER_TYPE_SALESMAN){
            member.setSalesManStatus(SundayCommonConstants.YES);
        }
        member.setUserType(type);
        member.setUserName(userName);
        member.setNickName(nickName);
        member.setMobile(mobile);
        member.setPassword(Digests.md5(password));
        super.save(member);
        return packageDtoSingle(member);
    }

    /**
     * 登录
     * @param mobile
     * @param password
     * @param loginType
     * @return
     */
    public SundayMemberDto login(String mobile, String password,Integer loginType){
        Map<String, Object> param =new HashMap<String,Object>();
        param.clear();
        param.put("isDeleted", 0);
        param.put("mobile", mobile);
        param.put("password", Digests.md5(password));
        List<SundayMember> members = super.list(param);
        if (ListUtil.isNull(members)) {
            throw new ErrorException("账户或密码错误");
        }
        if(loginType==SundayCommonConstants.LOGIN_TYPE_YONGHUBAN){
            param.put("userType in" , new Integer[]{SundayCommonConstants.USER_TYPE_MEMBER,SundayCommonConstants.USER_TYPE_SALESMAN});
        }else if(loginType==SundayCommonConstants.LOGIN_TYPE_GUANLIBAN){
            param.put("userType in" , new Integer[]{SundayCommonConstants.USER_TYPE_AGENT,SundayCommonConstants.USER_TYPE_SELLER});
        }else{
            throw new ErroException("登录类型错误");
        }
        SundayMember member=members.get(0);
        if (member.getStatus()!=0) {
            throw new ErrorException("账户被冻结");
        }

        return packageDtoSingle(member);
    }

    /**
     * 分页获取代理商的销售员或者维修工
     * @param request
     * @return
     */
    public List<SundayMemberDto> selectMember(HttpServletRequest request){
        Map<String,Object> param=ParamUtil.packageMongoExactParam(request,"userType","agentId");
        Map<String,String> containParam=ParamUtil.packageMongoVagueParam(request);
        return packageDtoMuilt(super.containpageQuery(request,containParam,param).getData());
    }

    /**
     * 通过手机号获取唯一账号
     * @param mobile
     * @return
     */
    public SundayMember getOneByMobile(String mobile,String code,SundayMember salesMan){
        int check_code=codeService.checkCode(mobile,code,SundayCommonConstants.validate_code_type_create_order);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("mobile",mobile);
        List<SundayMember> members=super.list(param);
        if(ListUtil.isNotNull(members)){
            return members.get(0);
        }else {
            SundayMember member=new SundayMember();
            member.setMobile(mobile);
            member.setRecommenderId(salesMan.getId());
            member.setAgentId(salesMan.getAgentId());
            super.save(member);
            return member;
        }
    }
    /**
     * 第三方登陆,第一步。只传入第三方信息。农厨第三方登陆需要绑定手机号
     * @param thirdType
     * @param unionId
     * @return
     */
    public SundayMemberDto loginWithThirdOne(Integer thirdType, String unionId){
        //校验用户
        Map<String, Object> param =new HashMap<String,Object>();
        param.clear();
        param.put("isDeleted",0);
        //校验第三方unionId
        if(thirdType==SundayCommonConstants.third_type_weixin){
            param.put("weixinUnionId",unionId);
        }else{
            throw new ErrorException("登陆类型错误");
        }
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNull(oldMembers)){
            //如果为空，调用第三方登陆，第二步
            return null;
        }
        return packageDtoSingle(oldMembers.get(0));
    }
    /**
     * 第三方登陆,第二步。传入第三方信息和手机号。农厨第三方登陆需要绑定手机号
     * @param thirdType
     * @param unionId
     * @param mobile
     * @return
     */
    public SundayMemberDto loginWithThirdTwo(Integer thirdType,String nickName,String image, String unionId, String mobile,String code) {

        //检验验证码
        int reulct_code =codeService.checkCode(mobile,code,SundayCommonConstants.validate_code_type_login);
        if(reulct_code!=0){
            throw new ErrorException("验证码错误");
        }
        //校验用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("mobile",mobile);
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNull(oldMembers)){
            //如果为空，调用第三方登陆，第三步
            return null;
        }
        //获取第三方信息。头像，昵称，unionId。替换用户的信息
        SundayMember member = oldMembers.get(0);
        member.setNickName(nickName);
        //保存unionId
        if(thirdType==SundayCommonConstants.third_type_weixin){
            member.setWeixinUnionId(unionId);
        }
        //获取第三方头像。半链接
        String random=String.valueOf(new Date().getTime());
        //如果当前项目的上传文件目录下没有logo文件夹，请自行创建。此文件夹存放的是默认的头像和第三方登陆用户头像
        String savePath = resourceHolder.getStringValue("fileUploadPath")+"/logo/"+random+".jpg";
        ImageUtils.buildImg(savePath,image);
        member.setImage("/logo/"+random+".jpg");
        super.updateExceptEmpty(member.getId(),member);
        SundayMemberDto memberDto=packageDtoSingle(member);

        return memberDto;
    }

    /**
     * 第三方登陆,第三步。传入第三方信息，手机号，密码，小区信息。农厨第三方登陆需要绑定手机号
     * @param thirdType
     * @param nickName
     * @param image
     * @param unionId
     * @param mobile
     * @param code
     * @param password
     * @return
     */
    public SundayMemberDto loginWithThirdThree(Integer thirdType,String nickName,String image, String unionId, String mobile,String code,String password) {
        //校验用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("mobile",mobile);
        //校验第三方unionId
        if(thirdType==SundayCommonConstants.third_type_weixin){
            param.put("weixinUnionId",unionId);
        }else{
            throw new ErrorException("登陆类型错误");
        }
        List<SundayMember> oldMembers = super.list(param);
        SundayMember member = new SundayMember();
        //创建用户
        if(ListUtil.isNull(oldMembers)){
            member.setIsDeleted(0);
            member.setStatus(0);
            member.setUserName(NumberUtil.generateNumber("APP"));
            member.setUserType(SundayCommonConstants.USER_TYPE_MEMBER);
            member.setMobile(mobile);
            member.setNickName(nickName);
            //member.setParentId(0l);
            //获取第三方头像。半链接
            String random=String.valueOf(new Date().getTime());
            //如果当前项目的上传文件目录下没有logo文件夹，请自行创建。此文件夹存放的是默认的头像和第三方登陆用户头像
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/logo/"+random+".jpg";
            ImageUtils.buildImg(savePath,image);
            member.setImage("/logo/"+random+".jpg");
            //保存unionId
            if(thirdType==SundayCommonConstants.third_type_weixin){
                member.setWeixinUnionId(unionId);
            }
            member.setPassword(Digests.md5(password));
            super.save(member);
            //返回用户信息。此步骤是避免接口端误操作第二步。
        }else{
            member=oldMembers.get(0);
        }
        SundayMemberDto memberDto=packageDtoSingle(member);
        //设置用户的token。暂时是用户的秘密
        // memberDto.setToken(member.getPassword());
        return memberDto;
    }

    /**
     * 退出登录。删除CID
     * @param memberId
     */
    public void logout(long memberId){
        cidService.clear(memberId);
    }

    /**
     * 修改个人信息
     * @param memberId
     * @param  nickName
     * @param mobileName
     * @param address
     * @param email
     * @param image
     * @param idCard
     * @param desc
     */
    public SundayMemberDto update(Long memberId,String nickName,String mobileName,String address,String email,
                                  String image,String idCard,String desc){

        SundayMember member = new SundayMember();
        member.setId(memberId);
        member.setNickName(nickName);
        member.setMobileName(mobileName);
        member.setAddress(address);
        //  member.setEmail(email);
        member.setImage(image);
        // member.setIdCard(idCard);
        member.setDesc(desc);
        super.updateExceptEmpty(memberId,member);
        return packageDtoSingle(super.getById(memberId));
    }

    /**
     * 忘记密码。
     * @param mobile
     * @param newPassword
     * @param code
     */
    public void forgetPassword(String mobile,String newPassword,String code){
        Map<String, Object> param =new HashMap<String,Object>();
        //校验验证码。
        int check_code=codeService.checkCode(mobile,code, SundayCommonConstants.validate_code_type_forget_password);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
        param.clear();
        param.put("isDeleted", 0);
        param.put("mobile", mobile);
        List<SundayMember> members = super.list(param);
        if(ListUtil.isNotNull(members)){
            SundayMember member = members.get(0);
            super.update(member.getId(),"password",Digests.md5(newPassword));
        }
    }
    /**
     * 修改密码。使用验证码
     * @param memberId
     * @param mobile
     * @param newPassword
     * @param code
     */
    public void updatePasswordWithCode(Long memberId,String mobile,String newPassword,String code){

        Map<String, Object> param =new HashMap<String,Object>();
        //校验验证码。
        int check_code=codeService.checkCode(mobile,code, SundayCommonConstants.validate_code_type_update_password);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
        param.clear();
        param.put("isDeleted", 0);
        param.put("mobile", mobile);
        List<SundayMember> members = super.list(param);
        if(ListUtil.isNotNull(members)){
            SundayMember member = members.get(0);
            super.update(member.getId(),"password",Digests.md5(newPassword));
        }
    }
    /**
     * 修改密码。使用旧密码
     * @param memberId
     * @param oldPassword
     * @param newPassword
     */
    public void updatePassword(Long memberId,String oldPassword,String newPassword){

        SundayMember member = super.getById(memberId);
        if (!Digests.md5(oldPassword).equalsIgnoreCase(member.getPassword())) {
            throw new ErrorException("旧密码错误");
        }
        super.update(memberId,"password",newPassword);
    }



    /**
     * 组装用户DTO。逻辑可以自定义
     */
    public SundayMemberDto packageDtoSingle(SundayMember member) {
        SundayMemberDto memberDto =new SundayMemberDto(
                member.getId(),member.getCreateTime(), member.getCreateDate(),
                member.getUserName(), member.getNickName(), member.getMobile(), member.getMobileName(), member.getAddress(), member.getEmail(),
                member.getUserType(),resourceHolder.getStringValue("imgRoot")+member.getImage(), member.getIdCard(),
                member.getDesc(),member.getStatus());

      /*  memberDto.setShareUrl(resourceHolder.getStringValue("mobileRoot")+"/sunday/mobile/member/share?id="+member.getId());
        memberDto.setShareImage(memberDto.getImage());
        memberDto.setShareTitle("珍珠集商城 用户推广");
        memberDto.setShareDesc("我是："+memberDto.getNickName()+",我为【珍珠集】代言，快来加入吧");
        //设置用户的token。暂时是用户的秘密*/
        // memberDto.setToken(member.getPassword());

        if (member.getDiscount()==null){

        }else {

            memberDto.setDiscount(new BigDecimal(member.getDiscount()));
        }
        memberDto.setSalesManStatus(member.getSalesManStatus());

        return  memberDto;
    }
    public List<SundayMemberDto>  packageDtoMuilt( List<SundayMember> members) {
        List<SundayMemberDto> dtos = new ArrayList<SundayMemberDto>();
        for(SundayMember member:members){
            dtos.add( packageDtoSingle(member));
        }
        return dtos;
    }


    /**
     * 获取用户详情
     * @param memberId
     * @return
     */
    public SundayMemberDto findOne(Long memberId){
        SundayMemberDto memberDto = packageDtoSingle(super.getById(memberId));
        //装载其他元素
        //是否收藏
        //用户评价。装载5个
        List<MdlCommentDto> comments = commentService.getCommentByNumber(5,memberId,SundayMember.class.getSimpleName());
        memberDto.setComments(comments);
        //产品列表。所有。
        // .. List<Long> productIds =permissionService.getPermission(Long.valueOf(memberId),1);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId",memberId);
        param.put("status",SundayCommonConstants.NO);
        //param.put("type",Finals.USER_TYPE_SELLER);
        return memberDto;
    }

    /**
     * 冻结或者启用销售员
     * @param salesManId
     * @param status
     */
    public void updateSalesManStatus(Long salesManId,Integer status){
        SundayMember salesMan=super.getById(salesManId);
        salesMan.setStatus(status);
    }

    /**
     * 代理商删除销售员
     * @param agentId
     * @param salesManId
     */
    public void deleteSalesMan(Long agentId,Long salesManId){
        SundayMember agent=super.getById(agentId);
        SundayMember salesMan=super.getById(salesManId);
        if(agent==null||salesMan==null){
            throw new ErrorException("系统错误");
        }
        if(salesMan.getAgentId().longValue()!=agentId.longValue()){
            throw new ErrorException("当前销售员不属于该代理商");
        }
        super.delete(salesManId);
    }

    /**
     * 获取默认代理商
     * @return
     */
    public Long getDefaultAgent(){
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("userType",SundayCommonConstants.USER_TYPE_AGENT);
        param.put("isDefaultAgent",SundayCommonConstants.YES);
        List<SundayMember> agents=super.list(param);
        if(ListUtil.isNotNull(agents)){
            return agents.get(0).getId();
        }else {
            return 0l;
        }
    }

}
